package cn.ulyer.core.modules.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.ulyer.common.jpa.entity.*;
import cn.ulyer.common.jpa.service.AbstractService;
import cn.ulyer.core.modules.system.service.RoleService;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;


@Service
public class RoleServiceImpl extends AbstractService<Role, Integer> implements RoleService {


    @Override
    protected JPAQuery<Role> buildPageQuery(Object queryModel) {
        Role role = (Role) queryModel;
        QRole qRole = QRole.role;
        JPAQuery<Role> jpaQuery = jpaQueryFactory.selectFrom(qRole);
        if (role != null) {
            if (StrUtil.isNotBlank(role.getName())) {
                jpaQuery.where(qRole.name.eq(role.getName()));
            }
            if (StrUtil.isNotBlank(role.getRoleValue())) {
                jpaQuery.where(qRole.roleValue.eq(role.getRoleValue()));
            }
        }
        return jpaQuery;
    }


    @Autowired
    private DataSource dataSource;

    @Override
    public List<Role> userRolesById(Long id) {
        QRole qrole = QRole.role;
        QUserRole userRole = QUserRole.userRole;
        QGroupRole qGroupRole = QGroupRole.groupRole;
        QUserGroup qUserGroup = QUserGroup.userGroup;

        JPAQuery<Role> query = jpaQueryFactory.selectFrom(qrole).where(
                qrole.id.in(JPAExpressions.select(userRole.roleId).from(userRole).where(userRole.userId.eq(id)))
                        .or(qrole.id.in(
                                JPAExpressions.select(qGroupRole.roleId.as("roleId")).from(qGroupRole).where(qGroupRole.groupId.in(
                                        JPAExpressions.select(qUserGroup.groupId).from(qUserGroup).where(qUserGroup.userId.eq(id))
                                ))
                        ))
        );
        return query.fetch();
    }


}
